﻿// Sheego.Service.X400
// Copyright(C) 2015 Schwab Versand GmbH
//
// This source file is subject to the Microsoft Public License(Ms-PL).
// http://www.opensource.org/licenses/ms-pl.html
// All other rights reserved.
using Sheego.Service.X400.Job.Shared.BO;
using Sheego.Service.X400.Job.Shared.Locator;
using Sheego.Service.X400.Job.Shared.Parser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sheego.Service.X400.Job.Impl.Parser
{
    class RangeParser : IRangeParser
    {
        #region IRangeParser Members

        public IRange Parse(string pattern)
        {
            if (String.IsNullOrWhiteSpace(pattern))
                throw new ArgumentNullException(pattern);

            var range = JobLocator.GetRange();
            foreach (var _elem in pattern.Split(new char[] { ',' }))
            {
                var elem = _elem;
                int step = 1;
                int si = elem.IndexOf('/');
                if (si > 0)
                {
                    step = Int32.Parse(elem.Substring(si + 1));
                    elem = elem.Substring(0, si);
                }

                int ix = elem.IndexOf('-');
                if (ix < 0)
                {
                    var v = Int32.Parse(elem);
                    range.Values.Add(v);
                    continue;
                }


                var v1 = Int32.Parse(elem.Substring(0 , ix));
                var v2 = Int32.Parse(elem.Substring(ix + 1));
                for(int i = v1;i <= v2; i+= step)
                    range.Values.Add(i);

            }

            return range;
        }

        #endregion
    }
}
